package org.yxt.message.push.config.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.yxt.message.netty.NettyServer;

/**
 * spring boot整个生命周期
 *
 * @author YangXiuteng
 * @time 2020/4/20 9:58
 **/
@Slf4j
public class ApplicationEventListener implements ApplicationListener {

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        // 在这里可以监听到Spring Boot的生命周期
        if (applicationEvent instanceof ApplicationEnvironmentPreparedEvent) {
            // 初始化环境变量
            log.info("初始化环境变量 ===>");
        } else if (applicationEvent instanceof ApplicationPreparedEvent) {
            // 初始化完成
            log.info("初始化完成 ===>");
        } else if (applicationEvent instanceof ContextRefreshedEvent) {
            // 应用刷新
            log.info("应用刷新 ===>");
        } else if (applicationEvent instanceof ApplicationReadyEvent) {
            // 应用已启动完成
            log.info("应用已启动完成 ===>");
            // 开启netty
            NettyServer.getInstance().closeNettyConn();
            NettyServer.getInstance().run();
        } else if (applicationEvent instanceof ContextStartedEvent) {
            // 应用启动，需要在代码动态添加监听器才可捕获
            log.info("应用开始启动 ===>");
        } else if (applicationEvent instanceof ContextStoppedEvent) {
            // 应用停止
            log.info("应用停止 <===");
        } else if (applicationEvent instanceof ContextClosedEvent) {
            // 应用关闭
            log.info("应用关闭 <===");
        }
    }
}